package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;

import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired(required = false)
    private UserService userService;

    @Autowired
    private  RedisTemplate redisTemplate;
    /**
     * @param user
     * @param session
     * @return
     */
    /**
     * 发验证码
     * @param user
     * @return
     */
    @RequestMapping("/sendMsg")
 /*   public R<String> sendMsg(@RequestBody User user, HttpSession session) {*/
    public R<String> sendMsg(@RequestBody User user) {
        //1. 获取手机号
        final String phone = user.getPhone();
        //2. 生成四位验证码
        final String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //3. 调用阿里的工具类发送短信
        /*SMSUtils.sendMessage("黑马旅游网", "SMS_205126318", phone, code);*/
        log.info("========本次验证:==========" + code);
        //4. 把验证码存储在Session中
        /*session.setAttribute(phone, code);  */
        redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
        //5. 返回信息
        return R.success("发送成功");
    }

    /**
     * 作用:登陆校验
     *
     * @param param
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> param, HttpSession session) {
        //1. 取出参数
        String phone = param.get("phone");
        log.info(phone);
         String code = param.get("code"); //用户输入的验证码
        log.info("用户输入的验证码"+code);
       /* String codeInSession = (String) session.getAttribute(phone);*/
      String codeInSession = (String) redisTemplate.opsForValue().get(phone);
       //2. 把参数交给Service 返回当前登录的对象
       User user = userService.login(phone, code, codeInSession);
        System.out.println(user);
        //登录成功做一个登录成功标记
        if(user!=null){
            redisTemplate.delete(phone);
            session.setAttribute("user",user.getId());
        }else {
            return R.error("登陆失败");
        }
        //3. 返回响应
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.invalidate();//清除session
        return  R.success("退出成功");
    }
}
